package com.ffyc.resale.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ffyc.resale.dao.UserDao;
import com.ffyc.resale.model.Account;
import com.ffyc.resale.model.Result;
import com.ffyc.resale.model.User;
import com.ffyc.resale.model.Yzm;
import com.ffyc.resale.util.JWTUtil;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.sql.Wrapper;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class UserService extends ServiceImpl<UserDao,User> implements IService<User>{
    @Autowired
    UserDao userDao;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    RedisTemplate redisTemplate;
    public Account login(Account account) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("email",account.getEmail()).eq("password", account.getPassword());
        User user = userDao.selectOne(wrapper);
        String token = JWTUtil.getToken(user);
        user.setToken(token);
        user.setRole("USER");
        return user;
    }

    public User findUserInfo(String userToken) {
        Integer id = JWTUtil.id(userToken);
        User user = userDao.selectById(id);
        return user;
    }

    public boolean updatePassword(Account account, String userToken) {
        if (!account.getNewPassword().equals(account.getConfirmPassword())){
            return false;
        }
        Integer id = JWTUtil.id(userToken);
        if(!userDao.selectById(id).getPassword().equals(account.getPassword())){
            return false;
        }
        lambdaUpdate()
                .set(Account::getPassword,account.getNewPassword())
                .eq(Account::getId,id)
                .update();
        return true;
    }

    public void updateUserInfo(User user, String userToken) {
        Integer id = JWTUtil.id(userToken);
        lambdaUpdate()
                .set(user.getName()!=null,User::getName,user.getName())
                .set(user.getAge()!=null,User::getAge,user.getAge())
                .set(user.getAvatar()!=null,User::getAvatar,user.getAvatar())
                .set(user.getGender()!=null,User::getGender,user.getGender())
                .set(user.getEmail()!=null,User::getEmail,user.getEmail())
                .eq(User::getId, id)
                .update();
    }
    public Page<User> getUser(User form){
        Page<User> userPage = new Page<>(form.getCurrentPage(),form.getPageSize());
        Page<User> userPage1 = userDao.selectPage(userPage, new QueryWrapper<>());
        return userPage1;
    }
    public void updateUser( User form){
        userDao.updateById(form);
    }
    public void addUser(User form){
        form.setName("未设置用户名");
        userDao.insert(form);
    }
    public void deleteUser(User form){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(form);
        userDao.delete(userQueryWrapper);

    }
    public Page<User> searchUser(User user){
        Page<User> userPage = new Page<>(user.getCurrentPage(),user.getPageSize());
        QueryWrapper<User> serach = new QueryWrapper<>();
        serach.like("name",user.getSearchQuery()).or().like("email", user.getSearchQuery());
        Page<User> userPage1 = userDao.selectPage(userPage, serach);
        return userPage1;
    }
    public Result CheckAccont(String email){
        User user = new User();
        user.setEmail(email);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>(user);

        if (userDao.selectList(queryWrapper).size()>=1){
            return new Result(200,"账号存在",1);
        }

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("2975857440@qq.com");//发送的qq邮箱
        message.setTo(email);//接收邮件的qq邮箱
        Random random = new Random();
        int randomNum = random.nextInt(1000000);
        String randomCode = String.format("%06d", randomNum);
        message.setSubject("主题：注册验证码");
        message.setText(randomCode);
        mailSender.send(message);
        //把验证码传入redis
        Yzm yzm = new Yzm();
        yzm.setData(0);
        yzm.setMessage(randomCode);
        return new Result(200,"账号不存在",yzm);
    }
    public Result login(User user){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(user);
        userQueryWrapper.eq("email", user.getEmail()).eq("password", user.getPassword());
        User user1 = userDao.selectOne(userQueryWrapper);
        if (user1==null){
            return new Result(201,"",false);
        }else {
            user1.setPassword("");
            user1.setUserToken(JWTUtil.getToken(user1));
            return new Result(200,"",user1);
        }
    }

    public int checkIsDz(Integer forumId, String userToken) {
        User user = JWTUtil.getUser(userToken);
        // 用redis存储，用户和新闻的点赞关系 userid+forumid:dz:1
        ValueOperations valueOperations = redisTemplate.opsForValue();
        if(redisTemplate.hasKey(user.getId()+":"+forumId+":dz")){// 用户点赞过
            return 1;
        }
        return 0;// 用户未点赞
    }

    public void dzoper(Integer forumId, Boolean isDZ, String userToken) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        User user = JWTUtil.getUser(userToken);
        System.out.println("用户id"+user.getId());
        if(isDZ){// 取消点赞
            valueOperations.decrement(forumId+":dzcount");//帖子点赞数量减一
            redisTemplate.delete(user.getId()+":"+forumId+":dz");// 删除帖子和用户的点赞关系
        }else{// 点赞
            // 再redis中添加一个键表示用户已经点过赞
            valueOperations.set(user.getId()+":"+forumId+":dz", 1);
            valueOperations.increment(forumId+":dzcount");// 点赞数量加1
        }
    }
}
